import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-07-13
 * Time: 10:14
 */

class IntCmp implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}
public class Test {

    public void createHeap(int[] array) {
        for(int i = (array.length-1-1)/2; i >= 0; i--) {
            shiftDown(array,i);
        }
    }
    private void shiftDown(int[] array,int parent) {
        int child = 2*parent-1;
        while(child < array.length) {
            if(child-1 < array.length && array[child] < array[child+1]) {
                child++;
            }
            if(array[child] > array[parent]) {
                swap(array[child],array[parent]);
            }else {
                break;
            }
            parent = child;
            child = 2*parent + 1;
        }
    }

    private void swap(int a,int b) {
        int tmp = a;
        a = b;
        b = tmp;
    }

    public int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        if(k <= 0) return ret;
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCmp());
        for(int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }

        for(int i = k; i < arr.length; i++) {
            int tmp = priorityQueue.peek();
            if(arr[i] < tmp) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }

        for(int i = 0; i < k; i++){
            ret[i] = priorityQueue.poll();
        }

        return ret;
    }



}
